<template>
  <PageWrapper dense contentClass="p-16px">
    <CollapseContainer title="订单信息">
      <BasicForm @register="registerForm">
        <template #customerId="{ model, field }">
          <Select v-model:value="model[field]" placeholder="请选择">
            <SelectOption v-for="item in state.customerList" :key="item.customerId" :value="item.customerId">
              {{ item.customerName }}
            </SelectOption>
          </Select>
        </template>
        <template #customerConcatId="{ model, field }">
          <Select v-model:value="model[field]" placeholder="请选择">
            <SelectOption v-for="item in state.userList" :key="item.userId" :value="item.userId">
              {{ item.userName }}
            </SelectOption>
          </Select>
        </template>
        <template #salesUserId="{ model, field }">
          <Select v-model:value="model[field]" placeholder="请选择">
            <SelectOption v-for="item in state.userList" :key="item.userId" :value="item.userId">
              {{ item.userName }}
            </SelectOption>
          </Select>
        </template>
      </BasicForm>
    </CollapseContainer>
    <transportEdit ref="transportEditRef" />
    <productEdit ref="productEditRef" />
    <executeEdit ref="executeEditRef" />
    <remarkEdit ref="remarkEditRef" />
    <div class="flex justify-end gap-8px mt-8px">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
import { BasicForm, useForm } from '@/components/Form';
import { ref, onMounted, reactive } from 'vue';
import { listCustomer } from '@/api/customer';
import { addSaleOrder, updateSaleOrder, getSaleOrder } from '@/api/sale/order';
import { userList } from '@/api/system/user';
import { drawerSchemas } from './order.data';
import { Select } from 'ant-design-vue';
import { CollapseContainer } from '@/components/Container';
import { PageWrapper } from '@/components/Page';
import transportEdit from './components/transportEdit.vue';
import productEdit from './components/productEdit.vue';
import executeEdit from './components/executeEdit.vue';
import remarkEdit from './components/remarkEdit.vue';
import { useTabs } from '@/hooks/web/useTabs';
import { useGo } from '@/hooks/web/usePage';
import { PageEnum } from '@/enums/pageEnum';
defineOptions({ name: 'saleOrderEdit' });
import { useRoute } from 'vue-router';
const SelectOption = Select.Option;
const { closeCurrent, setTitle } = useTabs();
/** 拿到路由的id */
const route = useRoute();
const isUpdate = (route.query.type as string) === 'update';
const id = route.query.id as string;
document.title = isUpdate ? '编辑订单' : '新增订单';
setTitle(document.title);
const go = useGo();
const emit = defineEmits(['register', 'reload']);

const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
  // layout: 'vertical',
  labelWidth: 100,
  name: 'user-drawer',
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: drawerSchemas,
});
const transportEditRef = ref();
const productEditRef = ref();
const executeEditRef = ref();
const remarkEditRef = ref();
async function handleSubmit() {
  const transportEditData = await transportEditRef.value?.handleSubmit();
  const productEditData = await productEditRef.value?.handleSubmit();
  const executeEditData = await executeEditRef.value?.handleSubmit();
  const remarkEditData = await remarkEditRef.value?.handleSubmit();
  if (
    !transportEditData ||
    !productEditData ||
    !executeEditData ||
    !remarkEditData
  )
    return;
  try {
    const data = {
      ...(await validate()),
      ...transportEditData,
      ...executeEditData,
      ...remarkEditData,
      status: 1,
      customerAddressId: '666666',
      list: productEditData.list.map((item: any) => {
        return {
          ...item,
          amount: item.num * item.price
        }
      })
    };

    if (isUpdate) {
      await updateSaleOrder(data);
    } else {
      const res = (await addSaleOrder(data)) as any;
      state.id = res;
    }
    handleCancel();
  } catch (e) {
    console.log('e', e);
  } finally {
  }
}

async function handleCancel() {
  resetForm();
  closeCurrent();
  go({ path: '/sale/order' as PageEnum });
}
const state = reactive({
  id: '',
  userList: [],
  customerList: [],
});
const getUserInfo = async () => {
  const res = (await getSaleOrder(id)) as any;
  res.customerTransactionId = res.customerTransactionId ? Number(res.customerTransactionId) : '';
  state.id = res.id;
  setFieldsValue(res);
  transportEditRef.value?.setFormData(res);
  productEditRef.value?.setFormData(res);
  executeEditRef.value?.setFormData(res);
  remarkEditRef.value?.setFormData(res);
};
const getUserData = async () => {
  const { rows } = await userList({ pageNum: 1, pageSize: 10000 });
  state.userList = rows;
};
const getCustomerData = async () => {
  const { rows }: any = await listCustomer({ pageNum: 1, pageSize: 10000 });
  state.customerList = rows;
};

onMounted(() => {
  getUserData();
  getCustomerData();
  id && getUserInfo();
});
</script>

<style lang="less" scoped>
:deep(.ant-tag) {
  margin-right: 6px;
  margin-bottom: 6px;
}
</style>
